package cool.houge.pig.infra.web;

import com.google.common.base.Strings;
import cool.houge.pig.BizErrors;
import cool.houge.pig.StacklessBizCodeException;
import cool.houge.pig.service.login.LoginChannelAuthentication;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * 登录通道拦截器.
 *
 * @author KK (kzou227@qq.com)
 */
@Component
public class LoginChannelInterceptor {

  private static final String PIG_LOGIN_CHANNEL_KEY_HEADER = "pig-login-channel-key";
  private static final String PIG_LOGIN_CHANNEL_PASSPHRASE_HEADER = "pig-login-channel-passphrase";

  private final LoginChannelAuthentication loginChannelAuthentication;

  public LoginChannelInterceptor(LoginChannelAuthentication loginChannelAuthentication) {
    this.loginChannelAuthentication = loginChannelAuthentication;
  }

  /**
   * @param handler
   * @return
   */
  public HandlerFunction<ServerResponse> handle(LoginChannelHandler handler) {
    return request -> {
      var key = request.headers().firstHeader(PIG_LOGIN_CHANNEL_KEY_HEADER);
      var passphrase = request.headers().firstHeader(PIG_LOGIN_CHANNEL_PASSPHRASE_HEADER);
      if (Strings.isNullOrEmpty(key)) {
        throw new StacklessBizCodeException(
            BizErrors.C810, "缺少HTTP Header参数 \"" + PIG_LOGIN_CHANNEL_KEY_HEADER + "\"");
      }

      return loginChannelAuthentication
          .authenticate(key, passphrase)
          .flatMap(loginChannel -> handler.handle(request, loginChannel));
    };
  }
}
